const cloud = require('wx-server-sdk');
// 初始化 cloud
cloud.init({
    // API 调用都保持和云函数当前所在环境一致
    env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database();
const _ = db.command;


/**
 * 这个示例将经自动鉴权过的小程序用户 openid 返回给小程序端
 * 
 * event 参数包含小程序端调用传入的 data
 * 
 */
exports.main = async(event, context) => {
    const response = {};
    const { OPENID } = cloud.getWXContext();
    const data = Object.assign({}, event, { openid: OPENID, created_time: new Date, updated_time: new Date })
    const _id = event._id;
    delete event._id;
    // query 传入_id,说明已存在该卡片，修改
    if (_id) {
        await db.collection('cards').doc(_id).update({
                data: Object.assign({}, event, { updated_time: new Date })
            })
            .then(() => {
                response.code = 200;
            })
            .catch(err => {
                response.error = err;
                response.code = 500;
            })
    } else {
        await db.collection('cards')
            .add({
                data
            })
            .then(() => {
                response.code = 200;
            })
            .catch((err) => {
                response.code = 500;
                response.error = err;
            })
    }
    return response;
}